let RoomId = "24748984";//直播房间号
let appId = "lb986e7a542bde48";//开发者appid
let keySignature = "4009314adae993cf4224c7da7f493339"; //开发者
let GameCtrl = class{
    constructor() {
        this.userInfos ={};//整体数据
        this.currentRoundUsers = [];//当前用户数据
        this.rankList = [];
        this.chatList = [];//指令列表
        // for (let index = 0; index < 11; index++) {
        //     this.addCurrentUser(Mock.mock({
        //         badgeName: "",
        //         color: ["@color"],
        //         "content|1-244": 0,
        //         fansLevel: 0,
        //         msgType: 0,
        //         nobleLevel: 0,
        //         roomId: 24748984,
        //         sendNick: "@cword(8)",
        //         senderAvatarUrl: "https://huyaimg.msstatic.com/avatar/1086/8b/20f0a993a018077489ea984058f666_180_135.jpg?1575302237",
        //         senderGender: 1,
        //         senderLevel: 1,
        //         unionId: "unzhCjmGfkp8lDcx5ijgJv7NoIXU8AwiaM",
        //     }));
        //     this.addUserInfo('unzhCjmGfkp8lDcx5ijgJv7NoIXU8AwiaM',Mock.mock({
        //         badgeName: "",
        //         color: ["@color"],
        //         "content|1-244": 0,
        //         fansLevel: 0,
        //         msgType: 0,
        //         nobleLevel: 0,
        //         roomId: 24748984,
        //         sendNick: "@cword(8)",
        //         senderAvatarUrl: "https://huyaimg.msstatic.com/avatar/1086/8b/20f0a993a018077489ea984058f666_180_135.jpg?1575302237",
        //         senderGender: 1,
        //         senderLevel: 1,
        //         unionId: "unzhCjmGfkp8lDcx5ijgJv7NoIXU8AwiaM",
        //     }));
        //     this.rankList.push(Mock.mock({
        //         badgeName: "",
        //         color: ["@color"],
        //         "content|1-244": 0,
        //         fansLevel: 0,
        //         msgType: 0,
        //         nobleLevel: 0,
        //         roomId: 24748984,
        //         sendNick: "@cword(8)",
        //         senderAvatarUrl: "https://huyaimg.msstatic.com/avatar/1086/8b/20f0a993a018077489ea984058f666_180_135.jpg?1575302237",
        //         senderGender: 1,
        //         senderLevel: 1,
        //         unionId: "unzhCjmGfkp8lDcx5ijgJv7NoIXU8AwiaM",
        //     }));
        // }
        this.doConnectRoom();
    }
    doConnectRoom(roomId){
        if(roomId!=undefined){
            RoomId = roomId;
        }
        console.log("-----doConnectRoom-------------"+RoomId);
        try {
            let newDateStr = Math.floor( Math.random()*10000)
            let socket = new WebSocket(this.getConnectUrl(RoomId));
            socket.onopen = (event) => {
                //发送subscribeNotice command
                socket.send(
                    `{"command":"subscribeNotice","data":["getMessageNotice","getSendItemNotice"],"reqId":${newDateStr}}`
                );
                //设置定时器以文本数据发送ping，保持与服务器的心跳
                setInterval(function () {
                    if(gCtrl.socket)
                    gCtrl.socket.send("ping");
                }, 15000);
            };
            socket.onerror = function (error) {
            console.log("error");
                gCtrl.onSocketError()
            };
            socket.onclose = function (error) {
                console.log("close");
                gCtrl.onSocketError()
            };
            var that = this;
            socket.onmessage = function (event) {
                var json = JSON.parse(event.data);
                if (json.statusCode === 200) {
                    if (json.notice === "getMessageNotice") {
                        //弹幕通知数据
                        gCtrl.onGetHuyaMessage(json.data)
                    }
                    else if(json.notice == 'getSendItemNotice')//送礼通知数据
                    {
                        gCtrl.onGetHuyaGift()
                    }
                } else {
                  //TODO 错误处理
                }
            };
            this.socket = socket;
        }
        catch (error) {
            console.log(error);
        }
    }
    //添加当前发指令的玩家
    addCurrentUser(data){
        // 长度为10的队列
        if (this.chatList.length < 9) {
            this.chatList.push(data);
        } else{
            this.chatList.shift();
            this.chatList.push(data);
        }
        for (var i = 0; i < this.currentRoundUsers.length; i++) {
            if(data.unionId == this.currentRoundUsers[i]){
                return;
            }
        }
        this.currentRoundUsers.push(data.unionId)
    }
    //添加用户列表 总表
    addUserInfo(unionId,data){
        if(this.userInfos[unionId]){
            return this.userInfos[unionId];
        }
        this.userInfos[unionId] = {
            sendNick:data.sendNick,
            point:0
        };
        return this.userInfos[unionId];
    }
    onGetHuyaMessage(data){
        console.log("onGetHuyaMessage"+JSON.stringify(data));
        this.addUserInfo(data.unionId,data);
        if(gCtrl.game){
            gCtrl.game.onGetHuyaMessage(data);
        }
    }
    onGetHuyaGift(data){

    }
    onSocketError(){
        if(gCtrl.socket){
            gCtrl.socket.close();
        }
        gCtrl.socket =  null;
        gCtrl.doConnectRoom(RoomId);
    }
    getConnectUrl(roomId){
        let jsonHeader = '{"alg":"HS256","typ":"JWT"}';
        let base64Header = window.btoa(jsonHeader);
        let curTime = Math.floor(new Date().getTime() / 1000);
        let endTime = Math.floor(curTime + 600);
        let jsonPayload = '{"iat":' + curTime + ',"exp":' + endTime + ',"appId":"' + appId + '"}';
        let base64Payload = window.btoa(jsonPayload);
        let strPayload = base64Payload.replace(/=/g, "");
        let strSignature = base64Header + "." + strPayload;
        
        let hash = CryptoJS.HmacSHA256(strSignature, keySignature);
        let hashInBase64 = CryptoJS.enc.Base64.stringify(hash);

        let s1 = hashInBase64.replace(/=/g, "");
        let s2 = s1.replace(/\+/g, "-");
        let base64Signature = s2.replace(/\//g, "_");

        let token = base64Header + "." + strPayload + "." + base64Signature

        let connectUrl = "wss://ws-apiext.huya.com/index.html?do=comm&roomId=" + roomId + "&appId=" + appId + "&iat=" + curTime + "&exp=" + endTime + "&sToken=" +token ;
            
        console.log(connectUrl);
        return connectUrl;
    }
    //画线
    //两端点p1,p2,线宽度w,颜色color
    createLine(x1,y1,x2,y2,w){
        let color = cc.color(255,255,255,255);
        let dx = x2-x1;
        let dy = y2-y1;
        let len = Math.sqrt(dx*dx+dy*dy);
        let deg =0
        if(dx==0){
            deg = dy>0?90:-90
        }else{
            let rad = Math.atan2(dy,dx);
            deg = rad*180/Math.PI;
        }
        let lineNode = new cc.LayerColor(color,len,w);
        lineNode.setAnchorPoint(cc.p(0,0));
        lineNode.setPosition(cc.p(x1,y1));
        lineNode.setRotation(-deg);
        return lineNode;
    }

    //画多边形
    //多边形顶点（按顺序），线条颜色
    createPolygonLines(arrs,color){
        let node = new cc.Node();
        for (var i = 0; i < arrs.length; i++) {
            let p1 = arrs[i];
            let p2 = arrs[i+1];
            if(i==arrs.length-1){
                p2 = arrs[0];
            }
            let line = this.createLine(p1.x,p1.y,p2.x,p2.y,3)
            line.setColor(color);
            node.addChild(line);
        }
        return node;
    }
    
};

window.gCtrl = new GameCtrl();
